<?php
/************************
 *  Codenova.pl Project
 *  Created by: Kamil Mrzygłód
 *
 *  (c) 2013 by Codenova.pl
 *  All Right Reserved
 ***********************/

namespace Modules\GotchaAdmin\Controllers;

use Gotcha\App\Extensions\HttpExtension;
use Gotcha\App\Framework\Controller;
use GotchaDatabase\GotchaModulesQuery;

class ModulesController extends Controller {
    public function Index() {
        return parent::View();
    }

    public function returnModules() {
        $modules = GotchaModulesQuery::create()
                        ->orderById()
                            ->find();

        // String builder
        $html = '';
        foreach($modules as $module) {
            $html .= '<tr>';
            $html .= sprintf('<td>%s</td><td>%s</td><td>[ <a href="%s?id=%s">%s</a> ]</td>', $module->getStrongName(), (($module->getIsActive() == 1) ? 'Tak' : 'Nie'), parent::UrlContent('/Admin/Modules/Activate'), $module->getId(), (($module->getIsActive() == 1) ? 'Deaktywuj' : 'Aktywuj'));
            $html .= '</tr>';
        }

        return $html;
    }

    public function Activate() {
        $http = new HttpExtension();

        // Validate input
        if(empty($_GET['id']) || !isset($_GET['id'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Modules?error=1'));
            exit;
        }

        // Activate/Deactivate
        try {
            $modules = GotchaModulesQuery::create()
                ->findOneById($_GET['id']);

            if($modules->getIsActive() == 1) {
                $modules->setIsActive(0);
            } else {
                $modules->setIsActive(1);
            }

            $modules->save();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Modules'));
        exit;

    }
}